import Fill from "ol/style/Fill";
import Icon from "ol/style/Icon";
import Stroke from "ol/style/Stroke";
import Style from "ol/style/Style";
import Text from "ol/style/Text";

export class olStyle {
  style;
  constructor(styleConfig) {
    this.style = this.createOpenlayerStyles(styleConfig);
  }

  /**
   * 创建openlayers样式对象
   * @param styleConfig 样式参数 { img: {}, stroke: {}, fill: 'rgba(0,0,0,0.5)'}
   */
  createOpenlayerStyles(styleConfig) {
    const currentStyle = new Style();
    if (styleConfig.img) {
      const imgStyle = this.createIconStyle(styleConfig.img);
      currentStyle.setImage(imgStyle);
    }
    if (styleConfig.fill) {
      const fillStyle = this.createFillStyle(styleConfig.fill);
      currentStyle.setFill(fillStyle);
    }
    if (styleConfig.stroke) {
      const strokeStye = this.createStrokeStyle(styleConfig.stroke);
      currentStyle.setStroke(strokeStye);
    }
    if (styleConfig.text) {
      const textStye = this.createTextStyle(styleConfig.text);
      currentStyle.setText(textStye);
    }
    return currentStyle;
  }

  /**
   * 创建图标样式
   * @param imgStyle 图标样式参数 { src: xxx/xxx.png, size: [32, 32] }
   */
  createIconStyle(imgStyle) {
    return new Icon({
      src: imgStyle.url,
      size: imgStyle.size,
      anchor: imgStyle["anchor"] || [0.5, 0.5],
    });
  }

  /**
   * 创建填充样式
   * @param color 颜色，rgba 或 十六进制颜色
   */
  createFillStyle(color) {
    return new Fill({
      color: color?color:'rgba(40,120,255,0.5)',
    });
  }

  /**
   * 创建描边样式
   * @param strokeStye 描边样式参数， { color: '#000000', width: 4, lineDash? , lineDashOffset? }
   */
  createStrokeStyle(strokeStye) {
    return new Stroke({
      color: strokeStye.color?strokeStye.color:'rgba(40,120,255,0.5)',
      width: strokeStye.width,
      lineDash: strokeStye.lineDash ? strokeStye.lineDash : undefined,
      lineDashOffset: strokeStye.lineDashOffset
        ? strokeStye.lineDashOffset
        : undefined,
    });
  }
  /**
   * 创建图层text文字样式
   */
  createTextStyle(textStye){
    return new Text({
      text: textStye.text,
      font: textStye.font?textStye.font:'14px Calibri,sans-serif',
      fill:this.createFillStyle(textStye.fill),
      stroke:this.createStrokeStyle(textStye.stroke),
      offsetX:textStye.offsetX,
      offsetY:textStye.offsetY,
      textAlign:textStye.textAlign,
      backgroundFill:this.createFillStyle(textStye.backgroundFill)

    });
  }
}
